<template>
  <!-- 提高一个层次，放置因为v-if没有正常销毁:change事件导致重复 -->
  <view :prop="uploadState"
        :change:prop="mask.drawMask"
  >
  <view v-if="!hidden">
    <view class="mb-30">
      <sub-title :title="standardListItem.projectName"></sub-title>
    </view>

    <!--拍照模块-->
    <view v-if="standardListItem.isTakePhoto" class="mb-30 pl-40">
      <text class="fz-32 color-888888 lh-45">拍照</text>
      <text class="fz-32 color-FF6262">*</text>
      <view class="flex flex-wrap">
        <!-- 图片缩略图 -->
        <view class="relative mr-30 mt-20" v-for="(item, index) in photoFiles" :key="index">
          <image
              class="h-150 w-150"
              :data-cur="item.url"
              :src="item.url"
              @tap="previewImage"
          />
          <!--  移除图片的按钮  -->
          <view class="absolute delBtn" @tap.stop="removeImage(index)">
            <image
                class="h-24 w-24"
                src="@/static/images/workList/delPhoto.png"
            />
          </view>
          <!-- 图片未上传标识 -->
          <view v-if="!item.isUploaded" class="absolute top0 bottom0 h-150 w-150 bg-00000060 color-fff fz-20 flex align-center justify-center" @tap="previewImage" :data-cur="item.url">
            <image
                class="h-24 w-24 mr-4"
                src="@/static/images/common/download.png"
            />
            <text>已缓存</text>
          </view>
        </view>
        <view v-if="photoFiles.length < 6" class="h-150 w-150 mt-20 bg-CCCCCC flex align-center justify-center" @tap="chooseImage">
          <image class="h-50 w-50" src="@/static/images/workList/camera.png"></image>
        </view>
      </view>
    </view>

    <!--  保养结果多选框  -->
    <view>
      <u-checkbox-group class="w-full">
        <view class="flex w-full flex-column">
          <view class="w-full flex align-center p-lr-20 mb-30" v-for="(item, index) in maintenanceType" :key="index">
            <u-checkbox
              @change="checkboxChange"
              shape="circle"
              active-color="#19BE6B"
              class="flex w-full border-333333 br-10 pl-20 h-100"
              label-size="32"
              v-model="item.checked"
              :name="item.name"
            >
              <text class="ml-20">{{item.label|| '-'}}</text>
            </u-checkbox>
          </view>
        </view>
      </u-checkbox-group>
    </view>

    <!--  数量输入框  -->
    <view>
      <view class="m-lr-20 p-lr-20 mb-30 pb-15 flex space-between align-center border-bottom-CCCCCC" v-if="isCheckedWash">
        <view class="fz-32 color-333333 lh-45 font-bold mr-40">
          <text class="color-FF6262">*</text>
          <text>清洗数量</text>
        </view>
        <u-input v-model="washValue" placeholder="点击输入数量" type="number" />
        </view>
    </view>

    <view>
      <view v-if="isCheckedReplace" class="m-lr-20 p-lr-20 mb-20 flex space-between align-center border-bottom-CCCCCC" >
        <view class="fz-32 color-333333 lh-45 font-bold mr-40">
          <text class="color-FF6262">*</text>
          <text>更换数量</text>
        </view>
        <u-input v-model="replaceValue" placeholder="点击输入数量" type="number" />
      </view>
<!--      <u-collapse  :accordion="false"  v-if="isCheckedReplace">
        <u-collapse-item :open="true"  @change="collapseDone">
          <template slot="title">
            <view class="lh-45 flex justify-between align-center">
              <view class="color-333333 font-bold fz-32 lh-45 flex">
                <view class="max-w-420 break-all">-{{ standardListItem.partName }}</view>
                <text class="pl-115" v-if="standardListItem.isUniqueCode">{{ `x${ recordList.length+replaceValue }` }}</text>
                <text class="pl-115" v-else>{{ `x${ replaceValue }` }}</text>

              </view>
            </view>
          </template>

              <view class="bg-gray br-5 p-20">
                <view class="flex align-center fz-28 color-333">
                  非条形码更换
                  <view class="ml-70 border-888888 color-888888 flex h-40 align-center text-center lh-38">
                    <view class="w-40 border-right-888 h-40" @tap.stop="down()">-</view>
                    <view class="w-80">{{ replaceValue }}</view>
                    <view class="w-40 border-left-888 h-40" @tap.stop="up()">+</view>
                  </view>
                </view>
                <view v-if="standardListItem.isUniqueCode" class="fz-28 align-center mt-20 mb-40 color-333">
                  条形码更换<text class="pl-100 color-888888">{{ recordList.length }}</text>
                </view>

                <view v-if="standardListItem.isUniqueCode" class="mb-20 bg-fff br-10">
                  <view class="p-tb-20 p-lr-20 relative" v-for="(part, cIdx) in recordList" :key="cIdx">
                    <view class="absolute top-20 right-20" @tap="removeSpareCode(cIdx)">
                      <u-icon name="close" size="24" color="#888888"></u-icon>
                    </view>
                    <view class="w-130 h-60 lh-60 text-center br-30 bg-FF9900 color-fff fz-28">
                      <text>{{ '-备件' + (cIdx + 1) }}</text>
                    </view>
                    <view class="flex align-center pl-14 mt-20 fz-26 justify-between">
                      <view @tap="scanOld(part)">
                        <uni-icons type="scan" size="30"></uni-icons>
                      </view>
                      <view class="p-lr-30">旧条形码</view>
                      <view class="border-CCCCCC br-10 h-56 flex align-center pl-14 flex1">
                        <u-input v-model="part.oldSpareBarcode" placeholder="点击输入条形码" />
                      </view>
                    </view>
                    <view class="flex align-center pl-14 fz-26 mt-12 justify-between">
                      <view @tap="scanNew(part)">
                        <uni-icons type="scan" size="30"></uni-icons>
                      </view>
                      <view class="p-lr-30">新条形码</view>
                      <view class="border-CCCCCC br-10 h-56 flex align-center pl-14 flex1">
                        <u-input v-model="part.newSpareBarcode" placeholder="点击输入条形码" />
                      </view>
                    </view>
                  </view>
                </view>

                <view v-if="standardListItem.isUniqueCode" @tap="addSpareCode">
                  <u-icon name="plus" size="30" color="#1582F5"></u-icon>
                  <text class="color-1582F5 fz-30 pl-7">
                    新增
                  </text>
                </view>

              </view>
            </u-collapse-item>
          </u-collapse>-->
    </view>


    <!--图片加水印画板-->
<!--    <canvas class="absolute top-99999"
            v-if="windowWidth !== 0 && windowHeight !== 0"
            :style="{'width':`${windowWidth}px`,'height': `${windowHeight}px`}"
            :canvas-id="uploadMaskImgCanvasId" >
    </canvas>-->

    <!--异常提示模态框-->
    <u-modal border-radius="20" :show-confirm-button="false" :show-title="false" mask-close-able v-model="isModalShow">
      <view class="min-h-150 p-tb-20 p-lr-20 flex align-center justify-center fz-30 font-bold color-333333">
        <image class="mr-20 min-w-38 w-38 h-38" src="@/static/images/mine/error.png"></image>
        <text>{{modalContent}}</text>
      </view>
    </u-modal>

    <u-mask :show="isShowMask" :mask-click-able="false">
      <view class="flex justify-center align-center h-full color-fff fz-32 font-bold">
        <text>提交中...</text>
        <u-loading mode="circle"></u-loading>
      </view>
    </u-mask>
  </view>
  </view>
</template>

<script>
import subTitle from "@/components/SubTitle/SubTitle";
import config from '@/config'
import dayjs from '@/libs/dayjs.min.js'
import PopupInput from "./PopUpInput.vue";
import {mapGetters} from 'vuex'
import { getPartListByIds } from "@/api/spare/part";
import uploadImg from '@/mixins/uploadImg'
import {base64ToPath} from '@/utils/upload'

export default {
  name: "CheckItem",
  components: {PopupInput, subTitle},
  mixins: [uploadImg],
  props: ['standardListItem','hospitalId','workOrderId','deviceName','workOrderName','isUseCache', 'hidden'],
  created () {
    const standard = this.standardListItem
    if(standard.partId){
      getPartListByIds({ids: standard.partId}).then(res=>{
        this.standardListItem.normalStock = res.data[0].normalStock || 0
      }).catch(err=> this.standardListItem.normalStock=0)
    }
  },
  data(){
    return {
      result: '',//单选多选结果
      originalResult: '',//单选多选原始结果
      photoFiles:[],//标准图片链接列表
      isShowUploadPhoto:true,//是否展示拍照模块
      modalContent: '',
      isModalShow: false,
      isShowMask: false,
      maintenanceType: [], //保养类型
      washValue: '',//清洗数量
      oldWashValue: '',
      originalWashValue: '', //上次提交的清洗数量
      replaceValue: null,//更换数量
      oldReplaceValue: null,
      originalReplaceValue: null, //上次提交的更换数量
      recordList:[],
      oldRecordList:[],
    }
  },
  watch:{
    isUseCache :{
      handler(isUseCache){
        const isHaveCache = !!this.maintenanceCache[this.workOrderId]
        const room_maintenance_cache = this.initStorage()
        //使用线上数据
        if(isUseCache === false || !isHaveCache){
          this.washValue = this.standardListItem.washValue
          this.oldWashValue = this.standardListItem.oldWashValue
          this.originalWashValue = this.standardListItem.washValue
          this.replaceValue = this.standardListItem.replaceValue === null || this.standardListItem.replaceValue === '' ? this.standardListItem.projectReplaceValue : this.standardListItem.replaceValue
          this.oldReplaceValue = this.standardListItem.oldReplaceValue
          this.originalReplaceValue = this.standardListItem.replaceValue || 0
          this.recordList = this.standardListItem.recordList || []
          this.oldRecordList = this.standardListItem.oldRecordList || []
          this.originalResult = this.standardListItem.result || ''
          this.photoFiles = this.standardListItem.images && this.standardListItem.images.length ? this.standardListItem.images.map(item => ({
            url:item.url,
            ossId: item.ossId,
            isUploaded: true
          })) : []
          if(this.standardListItem.maintenanceType.indexOf('1') > -1 && this.standardListItem.maintenanceType.indexOf('2') === -1){
            this.maintenanceType = [{name: '已清洗', label: `已清洗`, checked: false}].map(item => {
              if(this.standardListItem.result && this.standardListItem.result.indexOf(item.name) > -1){
                item.checked = true
              }
              return item
            })
          }
          if(this.standardListItem.maintenanceType.indexOf('2') > -1 && this.standardListItem.maintenanceType.indexOf('1') === -1){
            this.maintenanceType = [{name: '已更换', label: `更换${this.standardListItem.projectReplaceValue}个: ${this.standardListItem.partName}`, checked: false}].map(item => {
              if(this.standardListItem.result && this.standardListItem.result.indexOf(item.name) > -1){
                item.checked = true
              }
              return item
            })
          }
          if(this.standardListItem.maintenanceType.indexOf('1') > -1 && this.standardListItem.maintenanceType.indexOf('2') > -1){
            this.maintenanceType = [{name: '已清洗', label: `已清洗`, checked: false}, {name: '已更换', label: `更换${this.standardListItem.projectReplaceValue}个: ${this.standardListItem.partName}`, checked: false}].map(item => {
              if(this.standardListItem.result && this.standardListItem.result.indexOf(item.name) > -1){
                item.checked = true
              }
              return item
            })
          }
        }
        //使用本地缓存
        if(isUseCache === true && isHaveCache){
          const cache = room_maintenance_cache[this.workOrderId][this.standardListItem.workOrderDeviceProjectId]
          this.washValue = cache.washValue
          this.oldWashValue = cache.washValue
          this.originalWashValue = cache.washValue
          this.replaceValue = cache.replaceValue
          this.oldReplaceValue = cache.replaceValue
          this.originalReplaceValue = cache.replaceValue
          this.recordList = cache.recordList
          this.oldRecordList = cache.oldRecordList
          this.originalResult = cache.result
          this.photoFiles = cache.photoFiles || []
          this.maintenanceType = cache.maintenanceType || []
        }
        this.$emit('calcHeight')
      },
      immediate: true
    },
    washValue(newValue){
      this.isIllegalValue(newValue, 'washValue')
    },
    // replaceValue(newValue){
    //   this.isIllegalValue(newValue, 'replaceValue')
    // },
    maintenanceType:{
      handler(newValue){
        this.result = newValue.filter(item => item.checked).map(item => item.name).join(',')
      },
      deep: true,
      immediate: true
    }
  },
  computed:{
    ...mapGetters(['maintenanceCache']),
    // uploadMaskImgCanvasId() {
    //   return this.$u.guid()
    // },
    isCheckedWash(){
      return this.maintenanceType.some(item => {
        return item.name === '已清洗' && item.checked
      })
    },
    isCheckedReplace(){
      return this.maintenanceType.some(item => {
        return item.name === '已更换' && item.checked
      })
    }
  },
  methods: {
    collapseDone () {
      this.$emit('calcHeight')
    },
    //非条形码数量减少
    down () {
      if(this.replaceValue===0)return;
      //操作一条，库存加一条
      this.replaceValue -=1
      this.standardListItem.normalStock += 1
      },
    //非条形码数量增加
    up () {
      if(this.standardListItem.normalStock <= 0)return;
      //操作一条，库存减一条
      this.replaceValue +=1
      this.standardListItem.normalStock -= 1
    },
    //删除条形码
    removeSpareCode (index) {
      this.recordList.splice(index, 1)
      this.$emit('calcHeight')
    },
    // 新增条形码
    addSpareCode() {
      this.recordList.push({
        oldSpareBarcode:'',
        newSpareBarcode:''
      })
      this.$emit('calcHeight')
    },
    checkboxChange(){
      this.$emit('calcHeight')
    },
    isIllegalValue(value, type){
      switch (type) {
        case 'washValue':
          if((value && value.toString().indexOf('.') > -1) || value < 0 || value > 99) {
            this.isModalShow = true
            this.modalContent = '修改失败，请输入0-99的整数'
            this.$nextTick(() => {
              this.washValue = this.oldWashValue
            })
          } else {
            this.oldWashValue = value
          }
          break
        case 'replaceValue':
          if((value && value.toString().indexOf('.') > -1) || value < 1 || value > this.standardListItem.projectReplaceValue) {
            this.isModalShow = true
            this.modalContent = `修改失败，请输入1-${this.standardListItem.projectReplaceValue}的整数`
            this.$nextTick(() => {
              this.replaceValue = this.oldReplaceValue
            })
          } else {
            this.oldReplaceValue = value
          }
          break
      }
    },
    scanOld(part){
      uni.scanCode({
        scanType: ['barCode'],
        success: function (res) {
          part.oldSpareBarcode = res.result || ''
        }
      });
    },
    scanNew(part){
      uni.scanCode({
        scanType: ['barCode'],
        success: function (res) {
          part.newSpareBarcode = res.result || ''
        }
      });
    },
    initStorage(){
      const room_maintenance_cache = JSON.parse(JSON.stringify(this.maintenanceCache))
      if(!room_maintenance_cache[this.workOrderId]){
        room_maintenance_cache[this.workOrderId] = {}
      }
      if(!room_maintenance_cache[this.workOrderId][this.standardListItem.workOrderDeviceProjectId]){
        room_maintenance_cache[this.workOrderId][this.standardListItem.workOrderDeviceProjectId] = {}
      }
      return room_maintenance_cache
    },
    setStorage(){
      const room_maintenance_cache = this.initStorage()
      room_maintenance_cache[this.workOrderId][this.standardListItem.workOrderDeviceProjectId].washValue = this.washValue
      room_maintenance_cache[this.workOrderId][this.standardListItem.workOrderDeviceProjectId].replaceValue = this.replaceValue
      room_maintenance_cache[this.workOrderId][this.standardListItem.workOrderDeviceProjectId].maintenanceType = this.maintenanceType
      room_maintenance_cache[this.workOrderId][this.standardListItem.workOrderDeviceProjectId].recordList = this.recordList
      room_maintenance_cache[this.workOrderId][this.standardListItem.workOrderDeviceProjectId].result = this.result
      room_maintenance_cache[this.workOrderId][this.standardListItem.workOrderDeviceProjectId].photoFiles = this.photoFiles
      this.$store.commit('SET_MAINTENANCECACHE', room_maintenance_cache)
    },

    //提交数据前查看本地缓存有没有还没上传的照片
    async beforeEmitData(photoList, failCB){
      if(photoList.length){
        await new Promise((resolve, reject) => {
          let count = 0
          photoList.forEach((item, index) => {
            if(!item.ossId){
              const uploadTask = uni.uploadFile({
                url: config.baseUrl + '/system/oss/upload',
                filePath: item.url,
                name: 'file',
                header: {
                  Authorization: 'Bearer ' + this.$store.getters.token
                },
                success: (uploadFileRes) => {
                  const data = JSON.parse(uploadFileRes.data)
                  photoList[index] = {
                    url: data.data.url,
                    ossId: data.data.ossId,
                    isUploaded: true
                  }
                  count ++
                },
                fail: (err) => {
                  failCB(err)
                  count++
                  this.setStorage()
                }
              });
              setTimeout(() => {
                uploadTask.abort()
              }, 10000)
            }
            else{
              count ++
            }
          })
          let timer = setInterval(() => {
            if(count === photoList.length) {
              resolve()
              clearInterval(timer)
            }
          },1)
        })
      }
    },

    async emitData(){
      const failCB = (err) => {
        this.$emit('uploadCachePicFail')
      }
      let ossIdList = []
      if(this.standardListItem.isTakePhoto && this.photoFiles.length){
        await this.beforeEmitData(this.photoFiles, failCB)
        ossIdList = this.photoFiles.map(item => item.ossId)
      }
      const washValue = this.maintenanceType.find(item => item.name === '已清洗')?.checked ? this.washValue : ''
      let formData = {
        dataId: this.standardListItem.dataId,
        workOrderDeviceProjectId: this.standardListItem.workOrderDeviceProjectId,
        partId: this.standardListItem.partId,
        washValue,
        ossIdList,
        result: this.result,
        workOrderDeviceId: this.standardListItem.workOrderDeviceId,
        isTakePhoto: this.standardListItem.isTakePhoto,
      }
      if(this.maintenanceType.find(item => item.name === '已更换')?.checked){
        formData = {...formData, replaceValue: this.replaceValue}
        if(this.standardListItem.isUniqueCode){
          formData = {...formData, recordList: this.recordList}
        }
      }
      this.$emit('formData', formData)
    },
    isChange(){
      return this.result !== this.originalResult || this.washValue !== this.originalWashValue || this.replaceValue !== this.originalReplaceValue
    },
    // 上传图片
    chooseImage() {
      this.doChooseImageToBase64({
        maskInfo: {
          workOrderName: this.workOrderName || '-',
          deviceName: this.deviceName || '-',
          staffName: this.$store.getters.staffName || '-',
          time: dayjs().format('YYYY-MM-DD HH:mm:ss')
        }
      }, ()=>this.$emit('uploadStatusChange',true) ).finally(err => {
        this.$emit('uploadStatusChange',false)
      })
    },
    async uploadBase64(e) {
      if (!e || !e.dataURL) {
        this.$emit('uploadStatusChange',false)
        return Promise.reject('图片获取失败')
      }
      const dataURL = e.dataURL
      try {
        const tempFilePath = await base64ToPath(dataURL)
        await this.doUploadImage(tempFilePath)
          .then(res => {
            this.photoFiles.push({
              url: res.data.url,
              ossId: res.data.ossId,
              isUploaded: true
            })
            return Promise.resolve(res)
          })
          .catch(err => {
            this.photoFiles.push({
              url: tempFilePath,
              ossId: '',
              isUploaded: false
            })
            return Promise.reject(err)
          })
      } finally {
        // 重置上传状态，以防切换页面时重新触发上传
        const uploadState = {
          ...this.uploadState,
          tempFilePath: '',
        }
        this.uploadState = uploadState
        this.$emit('uploadStatusChange',false)
      }
    },
    // 点击预览
    previewImage(e) {
      const current = e.currentTarget.dataset.cur;
      const urls = [];
      this.photoFiles.forEach((el) => {
        urls.push(el.url);
      });
      uni.previewImage({
        current: current,
        urls: urls, //需要预览的图片链接列表
        indicator: "none", //图片指示器样式 "default" - 底部圆点指示器； "number" - 顶部数字指示器； "none" - 不显示指示器
      });
    },
    // 删除图片
    removeImage(index) {
      this.photoFiles.splice(index, 1)
      this.$emit('calcHeight')
    },
  },
  beforeDestroy(){
    clearInterval(this.timer)
  },
  options: {styleIsolation: "shared"},
}
</script>

<script module="mask" lang="renderjs">
export default {
  methods: {
    drawMask(newValue, oldVal, ownerInstance, instance) {
      // 解决事件没有销毁、初次进入会触发一次事件产生报错的问题
      if(!instance || !newValue || !newValue.tempFilePath) {
        return
      }
      try {
        const tempFilePath = newValue.tempFilePath.replace(/[\r\n]/g, "")
        const maskInfo = newValue.maskInfo || {}
        const params = newValue.params || {}
        const oCanvas = document.createElement('canvas')
        const oImg = document.createElement('img')
        oImg.src = tempFilePath
        oImg.onload = async () => {
          const { width, height } = oImg
          oCanvas.setAttribute('width', width)
          oCanvas.setAttribute('height', height)
          const ctx = oCanvas.getContext('2d')
          // 睡眠器，强制优先执行ctx.drawImage
          await new Promise((resolve) => {
            setTimeout(() => {
              ctx.drawImage(oImg, 0, 0, width, height)
              resolve()
            }, 500)
          })

          //设置画笔样式
          ctx.fillStyle = '#fff'
          ctx.lineWidth = 4;
          ctx.lineCap = "round"
          ctx.lineJoin = "round"
          ctx.font = `${width * 0.037}px sans-serif`
          // 水印
          ctx.strokeText(maskInfo.workOrderName || '-',width * 0.092,width * 0.18);
          ctx.fillText(maskInfo.workOrderName || '-', width * 0.092, width * 0.18)
          ctx.strokeText(maskInfo.deviceName || '-',width * 0.092,width * 0.23);
          ctx.fillText(maskInfo.deviceName || '-', width * 0.092, width * 0.23)
          ctx.strokeText(maskInfo.staffName || '-',width * 0.092,width * 0.28);
          ctx.fillText(maskInfo.staffName || '-', width * 0.092, width * 0.28)
          ctx.strokeText(maskInfo.time || '-',width * 0.092,width * 0.33);
          ctx.fillText(maskInfo.time || '-', width * 0.092, width * 0.33)

          const dataURL = oCanvas.toDataURL('image/jpeg', 0.5)
          this.$ownerInstance.callMethod('uploadBase64', {
            dataURL,
            params
          })
        }
      } catch {
        const params = newValue.params || {}
        this.$ownerInstance.callMethod('uploadBase64', {
          dataURL: '',
          params
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
/deep/ .u-radio__label {
  margin-left: 20rpx !important;
  padding: 24rpx 0 24rpx 24rpx !important;
  flex: 1 !important;
  width: 560rpx;
}
/deep/ .u-checkbox{
  width: 100% !important;
  display: flex !important;
  line-height: 1;
}
/deep/ .u-checkbox__label{
  flex: 1 !important;
  width: 560rpx;
  padding: 55rpx 0;
}
/deep/ .u-radio{
  width: 100% !important;
  display: flex !important;
  line-height: 1;
}
/deep/ .u-input__input{
  font-size: 32rpx !important;
}
.delBtn{
  top: -12rpx;
  right: -12rpx;
}
.options_container{
  max-height: 520rpx;
  overflow: scroll;
}
</style>
